package cube.io;

import java.io.Closeable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Scanner;

import cube.data.util.DataUtil;
import cube.utils.StringUtil;

/**
 * 流处理工具
 * 
 * @author abiao
 */
public class StreamUtil {

    /**
     * 标准输入
     */
    private static Scanner sc = new Scanner(System.in);

    /**
     * 读取一行字符
     */
    public static String readLine() {
        return sc.nextLine();
    }

    /**
     * 关闭流
     */
    public static void close(Socket sk, Closeable... closeables) {
        try {
            if (sk != null) {
                sk.close();
            }
            close(closeables);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭流
     */
    public static void close(Closeable... closeables) {
        try {
            for (Closeable closeable : closeables) {
                if (closeable != null) {
                    closeable.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从输入流中读取数据
     */
    public static String read(InputStream is, String charset) throws IOException {
        StringBuffer sb = new StringBuffer();
        try {
            byte[] buff = new byte[1024];
            int len;
            while ((len = is.read(buff)) != -1) {
                byte[] data = DataUtil.copy(buff, 0, len);
                sb.append(StringUtil.getString(data, charset));
            }
        } finally {
            StreamUtil.close(is);
        }
        return sb.toString();
    }

    /**
     * 将输入流中数据写入文件
     */
    public static void write(InputStream is, String file) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            byte[] buff = new byte[1024];
            int len;
            while ((len = is.read(buff)) != -1) {
                byte[] data = DataUtil.copy(buff, 0, len);
                fos.write(data);
            }
        } finally {
            StreamUtil.close(fos, is);
        }
    }
}
